package com.xb.loan.cashier.biz.task.bankcomm;

import com.xb.loan.cashier.biz.dao.bean.CashierPayChannel;
import com.xb.loan.cashier.biz.pay.bankcomm.BankcommConst;
import com.xb.loan.cashier.biz.pay.bankcomm.BankcommPayment;
import com.xb.loan.cashier.biz.service.CashierChargeOrderService;
import com.xb.loan.cashier.biz.service.CashierPayChannelService;
import com.xb.loan.cashier.biz.service.CashierPlatPaytypeService;
import com.xb.loan.cashier.biz.task.ThirdQueryChargeTask;
import com.xb.loan.cashier.biz.task.plat.PushChargeTask;
import com.xb.loan.cashier.service.constant.ICashierEnumConst;
import com.xb.loan.util.DateHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.Date;
import java.util.Map;

/**
 * 交行单笔查询任务
 */
@Component(value="bankcommQueryChargeTask")
@Scope(value="prototype")
public class BankcommQueryChargeTask extends ThirdQueryChargeTask {
    
    private static final Logger log = LoggerFactory.getLogger(BankcommQueryChargeTask.class);

    @Autowired
    private CashierChargeOrderService cashierChargeOrderService;
    @Autowired
    private CashierPayChannelService cashierPayChannelService;
    @Autowired
    private CashierPlatPaytypeService cashierPlatPaytypeService;
    
    @Override
	public void execute() {
	    String serialNo = null;
	    String tradeDateTime = null;
        String errorCode = null;
        String errorMsg = null;
        int status = 0;
        String orderId = cashierChargeOrder.getOrderId();
        String platId = cashierChargeOrder.getPlatId();
        String partnerId = cashierChargeOrder.getPartnerId();
        int payChannelType = cashierChargeOrder.getPayChannelType();
        String channelId = cashierChargeOrder.getPayChannelId();
        log.info("execute 开始处理订单 "+cashierChargeOrder.toString());
        CashierPayChannel cpc = cashierPayChannelService.queryByChannelId(channelId);
        if (cpc==null) {
            log.info("execute 支付渠道信息不存在 platId="+platId+",payChannelType="+payChannelType);
            return;
        }
        Map<String, Object> xmlResMap = BankcommPayment.queryOrder(cpc.getQueryUrl(), cpc.getChannelUser(), orderId);
        if (xmlResMap==null) {
        	log.info("execute xmlResMap is null");
			return;
		}
        Map<String, String> headResMap = (Map<String, String>)xmlResMap.get(BankcommConst.HEAD);
		String rspType = headResMap.get(BankcommConst.RSP_TYPE);
		if (BankcommConst.SUCC.equals(rspType)) {
			Map<String, Object> bodyResMap = (Map<String, Object>)xmlResMap.get(BankcommConst.BODY);
			Map<String, Object> orderListMap = (Map<String, Object>)bodyResMap.get("OrderList");
			if (orderListMap==null) {//订单不存在
				if (isTimeOut()) {//超时
	                status = ICashierEnumConst.CashierChargeStatus.FAIL.getStatus();
	                log.info("execute 第三方订单不存在并且已超时,该订单将会被处理为失败!");
	            }else {
	            	log.warn("execute 第三方订单不存在！  orderId="+orderId);
	                return;
	            }
			} else {
				Map<String, String> orderMap = (Map<String, String>)orderListMap.get("Order");
				int tranState = Integer.parseInt(orderMap.get("TranState"));
				String tranDate = orderMap.get("TranDate");
				String tranTime = orderMap.get("TranTime");
				serialNo = orderMap.get("SerialNo");
				try {
					Date date = DateHelper.convertToDate("yyyyMMddHHmmss", tranDate+tranTime);
					tradeDateTime = DateHelper.formatDate(null, date);
				} catch (ParseException e) {
					log.error(e.getMessage(),e);
					return;
				}
				//交易状态 0处理中 1成功 2失败 3异常 9未处理
				if (tranState==0 || tranState==9) {
					log.warn("execute 充值订单还未处理完成,终止运行！   orderId="+orderId);
					return;
				} else if (tranState==2 || tranState==3) {
					status = ICashierEnumConst.CashierChargeStatus.FAIL.getStatus();
				} else if (tranState==1) {
					status = ICashierEnumConst.CashierChargeStatus.SUCCESS.getStatus();
				}
			}
		}else {
			errorCode = headResMap.get(BankcommConst.RSP_CODE);
			errorMsg = headResMap.get(BankcommConst.RSP_MSG);
			log.warn("execute 查询订单异常,终止运行！  orderId="+orderId+",rspType="+rspType+",errorCode="+errorCode+",errorMsg="+errorMsg);
			return;
		}
		int res = cashierChargeOrderService.updateByOrderId(null,null,orderId,tradeDateTime,status,serialNo,errorCode,errorMsg);
		if (res>0) {
			PushChargeTask pct = (PushChargeTask)ctx.getBean("pushChargeTask");
			cashierChargeOrder.setStatus(status);
			pct.setCashierChargeOrder(cashierChargeOrder);
			pct.execute();
			log.info("execute 更新状态成功 orderId="+orderId+",platId="+platId+",partnerId="+partnerId);
		} else {
			int state = cashierChargeOrderService.queryStatus(orderId, null, null);
			if (state==ICashierEnumConst.CashierChargeStatus.WAIT.getStatus()) {
				log.info("execute 更新状态失败 orderId="+orderId+",platId="+platId+",partnerId="+partnerId);
			}
		}
	}
    
}
